package com.sskj.b70.v.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.SparseArray;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.MoneyValueFilter;
import com.sskj.b70.common.adapter.BaseAdapter;
import com.sskj.b70.common.adapter.ViewHolder;
import com.sskj.b70.common.decoration.DividerLineItemDecoration;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.common.widget.ToolBarLayout;
import com.sskj.b70.m.StockCoinBean;
import com.sskj.b70.m.bean.Entrust;
import com.sskj.b70.m.bean.TransactionModel;
import com.sskj.b70.m.bean.rxbus.StockCoin;
import com.sskj.b70.m.bean.rxbus.StockCoinUpdate;
import com.sskj.b70.p.fragment.TransactionPresenter;
import com.sskj.b70.utils.BottomSheetUtil;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.EditChangeUtil;
import com.sskj.b70.utils.MathUtil;
import com.sskj.b70.utils.NumberUtil;
import com.sskj.b70.utils.NumberUtils;
import com.sskj.b70.utils.RxSchedulersHelper;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.activity.BindMobileActivity;
import com.sskj.b70.v.activity.EntrustActivity;
import com.sskj.b70.v.activity.LoginActivity;
import com.sskj.b70.v.activity.MainActivity;
import com.sskj.b70.v.activity.MarketNewActivity;
import com.sskj.b70.v.base.BaseFragment;
import com.sskj.b70.v.widget.BubbleSeekBar;
import com.sskj.b70.v.widget.NumberRunningTextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

/**
 * 币币交易
 * create by Hey at 2018/4/26 9:14
 */
public class TransactionFragment extends BaseFragment<MainActivity, TransactionPresenter> {
    @BindView(R.id.max_trade_num)
    TextView maxTradeNum;// 最大交易数量  ----》买入 市价 时添加
    @BindView(R.id.priceNow)
    NumberRunningTextView mPriceNow;// 当前价格
    @BindView(R.id.changeRate)
    TextView mChangeRate;// 当前价格  右侧  百分比
    @BindView(R.id.highPrice)
    TextView mHighPrice;// 高 价格
    @BindView(R.id.tvRMB)
    TextView tvRMB;// 高 价格
    @BindView(R.id.transaction_rmb)
    TextView transactionRmb;// 人民币
    @BindView(R.id.lowPrice)
    TextView mLowPrice;   // 低  价格
    @BindView(R.id.transaction_sell_list)
    RecyclerView transactionSellList;
    @BindView(R.id.transaction_buy_list)
    RecyclerView transactionBuyList;
    @BindView(R.id.transaction_history_list)
    RecyclerView transactionHistoryList;
    @BindView(R.id.transaction_select_buy)
    RadioButton transactionSelectBuy;  // 买入
    @BindView(R.id.transaction_select_sell)
    RadioButton transactionSelectSell;   // 卖出
    @BindView(R.id.transaction_submit_order)
    TextView submitOrder;  // 买入按钮
    @BindView(R.id.transaction_history_all)
    TextView historyAll;  // 全部订单
    @BindView(R.id.transaction_now_price)
    TextView nowPrice;
    @BindView(R.id.transction_price_textView)
    TextView limitPrice;
    @BindView(R.id.transction_price_editText)
    EditText priceEdit;   // 价格输入框
    @BindView(R.id.transaction_num_edit)
    EditText numEdit;
    @BindView(R.id.transaction_type)
    TextView transactionType;
    @BindView(R.id.transaction_toolbar)
    ToolBarLayout toolBar;
    @BindView(R.id.transction_increase_price)
    TextView increase;
    @BindView(R.id.transction_decrease_price)
    TextView decrease;
    @BindView(R.id.transaction_count)
    TextView transactionTotal;
    @BindView(R.id.transaction_user_balance)
    TextView usefulNum;

    @BindView(R.id.spinner)
    TextView selectType;
    @BindView(R.id.loading_layout)
    FrameLayout mLoadingLayout;

    @BindView(R.id.transcation_seekbar)
    BubbleSeekBar transcationSeekbar;
    @BindView(R.id.llPriceMode)
    LinearLayout llPriceMode;  //市价 现价  显示栏

    @BindView(R.id.transaction_refresh)
    SmartRefreshLayout smartRefreshLayout;


    private double unit;

    //最新买卖条目
    private final int buyNum = 5;
    /**
     * 委托记录adapter
     */
    private BaseAdapter<Entrust> transactionAdapter;
    private BaseAdapter<TransactionModel.AsksBean> sellAdapter;
    private BaseAdapter<TransactionModel.BidsBean> buyAdapter;


    private DecimalFormat priceFormat = new DecimalFormat("0.00000000");
    private DecimalFormat numFormat = new DecimalFormat("0.00000000");


    private BigDecimal realPrice = new BigDecimal("0");

    //用户余额
    private String money = "0.0";
    /**
     * 币种名称
     */
    private String name = "";
    /**
     * 币种编码
     */
    private String code = "";

    /**
     * 000
     * 最大数量
     */
    private double max = 0;
    /**
     * 最小数量
     */
    private double min = 0;


    private static final int SHIJIA = 1;
    private static final int XIANJIA = 2;

    //手续费
    private double transFee = 0;

    //持有币的数量
    private String haveNum = 0 + "";


    /**
     * 价格类型 ： 1: 市价   ；   2 ： 限价
     * 默认 限价
     */
    private int orderType = XIANJIA;
    private String unitCoin = "USDT";


    private String currencyType = "";
    private BottomSheetDialog priceModeSheet;
    private StockCoin mSockCoin;
    private String usdtMoney = "0.0";
    private BigDecimal maxBig;

    public static TransactionFragment newInstance(String code) {

        Bundle args = new Bundle();
        args.putString(Constants.CODE, code);
        TransactionFragment fragment = new TransactionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_transaction;
    }

    @Override
    public TransactionPresenter getPresenter() {
        return new TransactionPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }
    public boolean checkPhone() {
        if (TextUtils.isEmpty(MyAppLication.getMobile())) {
            ToastUtil.showShort(getString(R.string.mine_bind_phone));
            BindMobileActivity.start(getActivity());
            return false;
        }
        return true;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (MyAppLication.isLogin()) {
                if (mPresenter != null) {
                    mPresenter.getUserInfo();
                    mPresenter.getPankou(code);
                    mPresenter.getStockCoinByCode(code);
                    mPresenter.getNewInfo(code);
                }
            } else {
                updateWallet("0");
            }
        }
    }

    @Override
    public void initView() {
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
        if (getArguments() != null) {
            code = getArguments().getString(Constants.CODE, Constants.DEFAULT_COIN);
        }
        toolBar.setRightButtonIcon(getResources().getDrawable(R.mipmap.icon_a_nor));
        toolBar.setRightButtonOnClickLinster(view12 -> { //跳转股票详情
            MarketNewActivity.start(getActivity(), code);
        });

        //当前委托
        ClickUtil.click(historyAll, () -> {
            if (MyAppLication.isLogin()) {
                EntrustActivity.start(mActivity, code);
            }
        });

        initRecyclerView();
        initAdapter();
        initListener();
        numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
        priceEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
        mPresenter.getStockCoinByCode(code);
        mPresenter.getPankou(code);
    }

    //    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setSockCoin(StockCoin mSockCoin) {
        this.mSockCoin = mSockCoin;
        code = mSockCoin.getName();
        mPresenter.getPankou(code);
        orderType = XIANJIA;
        upDate();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateSockCoin(StockCoinUpdate stockCoinUpdate) {
        code = stockCoinUpdate.getCode();
        mPresenter.getPankou(code);
        mPresenter.getStockCoinByCode(stockCoinUpdate.getCode());
        mPresenter.getNewInfo(code);
    }

    /**
     * 更新盘口最新价
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateNewPrice(StockCoinBean.StockProductVOBean stockProductVOBean) {
        if (stockProductVOBean != null && code.equals(stockProductVOBean.getCode()) && getActivity() != null) {
            if (mSockCoin != null) {
                mSockCoin.setBuyPrice(stockProductVOBean.getBuy() + "");
                mSockCoin.setSellPrice(stockProductVOBean.getSell() + "");
            }
            if (!TextUtils.isEmpty(stockProductVOBean.getPrice())) {
                setText(nowPrice, stockProductVOBean.getPrice());
                if (transactionRmb != null) {
                    transactionRmb.setText("≈" + stockProductVOBean.getCnyPrice() + "CNY");
                }
                if (tvRMB != null) {
                    tvRMB.setText("≈" + stockProductVOBean.getCnyPrice() + "CNY");
                }
            }
            if (stockProductVOBean.getChange() > 0) {
                mChangeRate.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
                mPriceNow.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
                nowPrice.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
            } else {
                mChangeRate.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
                mPriceNow.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
                nowPrice.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
            }
            mChangeRate.setText(stockProductVOBean.getChangeRate());
            mHighPrice.setText(NumberUtil.keepMax8(stockProductVOBean.getHigh()));
            mLowPrice.setText(NumberUtil.keepMax8(stockProductVOBean.getLow()));
            mPriceNow.setText(stockProductVOBean.getPrice());
        }


    }

    @Override
    public void initData() {
        upDate();
    }


    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        transactionHistoryList.setLayoutManager(linearLayoutManager);
        transactionSellList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, true));
        transactionBuyList.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        transactionHistoryList.addItemDecoration(new DividerLineItemDecoration(mActivity)
                .setPaintColor(ContextCompat.getColor(mActivity, R.color.line_color)));
    }

    /**
     * 初始化Adapter,数据集为空
     */
    private void initAdapter() {
        transactionAdapter = new BaseAdapter<Entrust>(R.layout.item_recycler_entrust, new ArrayList<>(), transactionHistoryList, true) {
            @Override
            public void bind(ViewHolder holder, Entrust item) {
                if (item.getStockName() == null || item.getStockName().split("/").length == 1) {
                    item.setStockName("ETH/USDT");
                }
                SpannableString spannableString17 = new SpannableString(item.getStockName());
                RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.7F);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                        Color.parseColor("#AABBCC"));
                StyleSpan styleSpan = new StyleSpan(Typeface.NORMAL);
                spannableString17.setSpan(relativeSizeSpan, item.getNumUnit().length(), item.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString17.setSpan(foregroundColorSpan, item.getNumUnit().length(), item.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString17.setSpan(styleSpan, item.getNumUnit().length(), item.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                holder.setText(R.id.item_entrust_name, spannableString17)
                        .setText(R.id.item_entrust_type, item.getTradeType() == 1 ? App.INSTANCE.getString(R.string.strTransactionFragment19) : App.INSTANCE.getString(R.string.strTransactionFragment20))
                        .setTextColor(R.id.item_entrust_type, ContextCompat.getColor(getActivity(), item.getTradeType() == 1 ? R.color.market_down : R.color.market_up))
//                        .setText(R.id.item_entrust_time, TimeFormatUtil.SF_FORMAT_G.format(new Date(TimeFormatUtil.parseLongE(item.getCreateTime()))))
                        .setText(R.id.item_entrust_time, item.getCreateTime() + "")
                        .setText(R.id.item_entrust_price, item.getEntrustPrice() + "")
                        .setText(R.id.item_entrust_price_text, App.INSTANCE.getString(R.string.strTransactionFragment171) + item.getPriceUnit() + ")")
                        .setText(R.id.item_entrust_real_num_text, App.INSTANCE.getString(R.string.strTransactionFragment173) + item.getNumUnit() + ")")
                        .setText(R.id.item_entrust_real_num, item.getEntrustNum() + "")
                        .setText(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strTransactionFragment176) + item.getNumUnit() + ")")
                        .setText(R.id.item_entrust_num, NumberUtil.keepMax(item.getEntrustNum(), 8));
                if (item.getBillPriceType() == 1 && item.getTradeType() == 1) {  //市价买入
                    holder.setText(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strTransactionFragment30))
                            .setText(R.id.item_entrust_num, item.getTotalPrice() + "");
                } else { //其他
                    holder.setText(R.id.item_entrust_num_text, App.INSTANCE.getString(R.string.strTransactionFragment176) + item.getNumUnit() + ")")
                            .setText(R.id.item_entrust_num, item.getDealNum() + "");
                }
                if (item.getBillPriceType() == 1) {//市价
                    holder.setText(R.id.item_entrust_price, App.INSTANCE.getString(R.string.strTransactionFragment35));
                } else {
                    holder.setText(R.id.item_entrust_price, item.getEntrustPrice() + "");
                }
                TextView cancel = holder.getView(R.id.item_entrust_cancel);
                switch (item.getState()) {
                    case 0:
                    case 1:
                        cancel.setText(R.string.coin_cancel);
                        cancel.setOnClickListener(v -> mPresenter.cancelOrder(item.getTradeType(), item.getId() + ""));
                        cancel.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_light_white));
                        break;
                    case 2:
                        cancel.setText(R.string.coin_finished);
                        cancel.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_light_white));
                        break;
                    case 3:
                        cancel.setText(R.string.coin_cancled);
                        cancel.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_light_white));
                        break;
                }
            }
        };
        sellAdapter = new BaseAdapter<TransactionModel.AsksBean>(R.layout.item_recycler_transaction_sell, new ArrayList<>(), transactionSellList) {
            @Override
            public void bind(ViewHolder holder, TransactionModel.AsksBean item) {
                holder.setText(R.id.transaction_sell_id, holder.getLayoutPosition() + 1 + "");
                holder.setText(R.id.transaction_sell_price, unitCoin.contains("USDT") ? NumberUtil.keep4(item.getPrice()) : item.getPrice());
                holder.setText(R.id.transaction_sell_num, NumberUtil.keep4(item.getTotalSize()));
                holder.getView(R.id.transaction_sell_item).setOnClickListener(view -> {
                    if (orderType == XIANJIA) {
                        setTextAndAnim(unitCoin.contains("USDT") ? NumberUtil.keep4(item.getPrice()) : item.getPrice());
                    } else {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment39));
                    }
                });
            }
        };
        buyAdapter = new BaseAdapter<TransactionModel.BidsBean>(R.layout.item_recycler_transaction_sell, new ArrayList<>(), transactionBuyList) {
            @Override
            public void bind(ViewHolder holder, TransactionModel.BidsBean item) {
                holder.setText(R.id.transaction_sell_id, holder.getLayoutPosition() + 1 + "");
                holder.setText(R.id.transaction_sell_price, unitCoin.contains("USDT") ? NumberUtil.keep4(item.getPrice()) : item.getPrice());
                holder.setText(R.id.transaction_sell_num, NumberUtil.keep4(item.getTotalSize()));
                holder.setTextColor(R.id.transaction_sell_price, ContextCompat.getColor(getActivity(), R.color.bull_cyan_blue));
                holder.getView(R.id.transaction_sell_item).setOnClickListener(view -> {
                    if (orderType == XIANJIA) {
                        setTextAndAnim(unitCoin.contains("USDT") ? NumberUtil.keep4(item.getPrice()) : item.getPrice());
                    } else {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment39));
                    }
                });
            }
        };

    }


    public void submitOrderSuccess(String msg) {
        ToastUtil.showShort(msg);
        mPresenter.getEntrustList(code);
        mPresenter.getUserInfo();
        mPresenter.getStockCoinByCode(code);
    }

    public void submitOrderFail(String msg) {
        ToastUtil.showShort(msg);
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        smartRefreshLayout.setRefreshHeader(new MaterialHeader(mActivity));
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            smartRefreshLayout.finishRefresh();
            if (MyAppLication.isLogin()) {
                mPresenter.getEntrustList(code);
                mPresenter.getUserInfo();
                mPresenter.getStockCoinByCode(code);

            } else {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment42));
            }
            mPresenter.getStockCoinByCode(code);
        });

        //提交订单
        ClickUtil.click(submitOrder, () -> {
            if (MyAppLication.isLogin()) {  // 是否登录
                if (!checkPhone()){
                    return;
                }
                String price = "";
                String num = numEdit.getText().toString().trim();

                if (orderType == XIANJIA) { //限价
                    price = priceEdit.getText().toString().trim();

                    if (TextUtils.isEmpty(price)) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment44));
                        return;
                    }
                    if (Double.valueOf(price) <= 0) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment45));
                        return;
                    }

                    if (TextUtils.isEmpty(num)) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment46));
                        return;
                    }
                    if (Double.valueOf(num) <= 0) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment47));
                        return;
                    }

                    if (mActivity.status == 0) { //买
                        mPresenter.submit(code, price, num, 1, 2);
                    } else { //卖
                        mPresenter.submit(code, price, num, 2, 2);
                    }
                } else { //市价
                    if (TextUtils.isEmpty(num)) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment46));
                        return;
                    }

                    if (Double.valueOf(num) <= 0) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment47));
                        return;
                    }
                    if (mActivity.status == 0) { //买
                        mPresenter.submit(code, limitPrice.getHint().toString().trim(), num, 1, 1);
                    } else { //卖
                        mPresenter.submit(code, limitPrice.getHint().toString().trim(), num, 2, 1);
                    }
                }
            } else {
                Intent intent = new Intent(mActivity, LoginActivity.class);
                intent.putExtra("from", "transaction");
                startActivityForResult(intent, Constants.TRANSACTION);
            }
        });

        //增加价格
        ClickUtil.click(200, increase, () -> {
                    realPrice = realPrice.add(new BigDecimal(unit + ""));
                    priceEdit.setText(NumberUtil.keepMax8(realPrice.toString()));
                }
        );
        //减少价格
        ClickUtil.click(200, decrease, () -> {
            if (realPrice.doubleValue() > 0) {
                realPrice = realPrice.add(new BigDecimal(-unit + ""));
                priceEdit.setText(NumberUtil.keepMax8(realPrice.toString()));
            }
        });

        toolBar.setLeftButtonOnClickLinster(view -> {
            mActivity.mIsTransactionOpenDrawer = true;
            mActivity.openDrawerLayout();
        });
        ClickUtil.click(llPriceMode, () -> {
            if (priceModeSheet == null) {
                priceModeSheet = BottomSheetUtil.getBottomSheet(getActivity(), App.INSTANCE.getString(R.string.strTransactionFragment54), (recyclerView, position, v) -> {
                    priceModeSheet.dismiss();
                    changePriceMode(position);
                }, App.INSTANCE.getString(R.string.strTransactionFragment35), App.INSTANCE.getString(R.string.strTransactionFragment56));
            }
            priceModeSheet.show();
        });
        transactionSelectBuy.setOnCheckedChangeListener((buttonView, isChecked) -> {//买入
            if (isChecked) {
                transactionSelectSell.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_gray));
                transactionSelectBuy.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_down));
                mActivity.status = 0;
                checkLogin();
                numEdit.getText().clear();
                switchPrice();
                calculateMaxMin();
                if (orderType == SHIJIA) {
                    numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
                } else {
                    numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
                }

                transcationSeekbar.setSecondTrackColor(ContextCompat.getColor(mActivity, R.color.market_down));
                transcationSeekbar.setThumbColor(ContextCompat.getColor(mActivity, R.color.market_down));
                transcationSeekbar.setBubbleColor(ContextCompat.getColor(mActivity, R.color.market_down));
            }

        });

        transactionSelectSell.setOnCheckedChangeListener((buttonView, isChecked) -> {//卖出
            if (isChecked) {
                mActivity.status = 1;
                checkLogin();
                transactionSelectSell.setTextColor(ContextCompat.getColor(getActivity(), R.color.market_up));
                transactionSelectBuy.setTextColor(ContextCompat.getColor(getActivity(), R.color.bull_gray));
                numEdit.getText().clear();
                switchPrice();
                calculateMaxMin();
                numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});

                transcationSeekbar.setSecondTrackColor(ContextCompat.getColor(mActivity, R.color.market_up));
                transcationSeekbar.setThumbColor(ContextCompat.getColor(mActivity, R.color.market_up));
                transcationSeekbar.setBubbleColor(ContextCompat.getColor(mActivity, R.color.market_up));
            }
        });

        transcationSeekbar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                if (fromUser) {
                    double num;
                    num = progressFloat;
                    if (progressFloat >= (int) max) {
                        num = max;
                    }
                    numEdit.setText(priceFormat.format(num));
                    calculateTotalPrice();
                }
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }
        });

        EditChangeUtil.onChange(numEdit, s -> {
            if (!MyAppLication.isLogin()) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment42));
                return;
            }
            if (NumberUtils.pareFloat(s.toString()) > transcationSeekbar.getMax()) {
                transcationSeekbar.setProgress(transcationSeekbar.getMax());
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strTransactionFragment58));
            } else {
                transcationSeekbar.setProgress(NumberUtils.pareFloat(s.toString()));
            }
            calculateTotalPrice();

        });
        EditChangeUtil.onChange(priceEdit, s -> {
            if (TextUtils.isEmpty(s)) {
                realPrice = new BigDecimal("0");
            } else {
                realPrice = new BigDecimal(s.toString());
            }
            calculateMaxMin();
            calculateTotalPrice();
        });
    }

    /**
     * 切换市价限价，0 市价，1 限价
     *
     * @param position
     */
    private void changePriceMode(int position) {
        if (position == 0) { //市价
            selectType.setText(App.INSTANCE.getString(R.string.strTransactionFragment35));
            priceEdit.setVisibility(View.INVISIBLE);
            limitPrice.setVisibility(View.VISIBLE);
            orderType = SHIJIA;
            calculateMaxMin();
            calculateTotalPrice();
        } else { //限价
            selectType.setText(App.INSTANCE.getString(R.string.strTransactionFragment56));
            priceEdit.setVisibility(View.VISIBLE);
            limitPrice.setVisibility(View.INVISIBLE);
            orderType = XIANJIA;
            calculateMaxMin();
            calculateTotalPrice();
        }
        if (mActivity.status == 0) {
            if (position == 0) {
                numEdit.getText().clear();
                numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
            } else {
                numEdit.getText().clear();
                numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});

            }
        } else {
            numEdit.getText().clear();
            numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
        }
    }


    /**
     * 委托记录
     *
     * @param data 数据源
     */
    public void setHistory(List<Entrust> data) {
        if (transactionAdapter != null) {
            if (data.size() > 5) {
                transactionAdapter.setNewData(data.subList(0, 5));
            } else {
                transactionAdapter.setNewData(data);
            }
        }
    }

    /**
     * 取消订单
     *
     * @param message 返回信息
     * @param success 是否成功取消
     */
    public void cancelOrder(String message, boolean success) {
        ToastUtil.showShort(message);
        if (success) {
            mPresenter.getEntrustList(code);
            mPresenter.getUserInfo();
            mPresenter.getStockCoinByCode(code);

        }
    }


    /**
     * 计算加减单位
     */
    public void calculateUnit() {
        String text = priceEdit.getText().toString().trim();
        double price = 0;
        if (!TextUtils.isEmpty(text)) {
            price = Double.parseDouble(text);
        }
        int length = text.length();
        int index = 0;
        if (text.contains(".")) {
            index = text.indexOf(".");
        }
        int x = length - index - 1;
        if (price == 0) {
            unit = 1;
        } else {
            unit = MathUtil.divide(1, Math.pow(10, x));
        }
    }


    /**
     * 更新界面信息
     */

    public void upDate() {
        mPresenter.getNewInfo(code);

        currencyType = code.split("/")[0];
        checkLogin();
        if (mSockCoin == null) return;
        if (!TextUtils.isEmpty(mSockCoin.getPrice())) {
            setText(nowPrice, mSockCoin.getPrice());
        }
        selectBuySell();
        changeCoinData();
        if (MyAppLication.isLogin()) {
            transactionAdapter.setNewData(new ArrayList<>());
            mPresenter.getEntrustList(code);
        }

        mActivity.mTransactionFragmentUp = true;
        unitCoin = name.split("/")[1];
        changePriceMode(1);
        calculateUnit();
        calculateMaxMin();
    }


    /**
     * 切换币种信息
     * 更新name,code和最新价格
     * 更新长连接
     */
    private void changeCoinData() {
        if (mSockCoin != null) {
            name = mSockCoin.getName();
            transFee = mSockCoin.getTransFee() / 100d;
            haveNum = mSockCoin.getHaveNum();
            money = usdtMoney = mSockCoin.getMoney();

            numEdit.getText().clear();
            if (!name.toUpperCase().contains(currencyType)) {
                mLoadingLayout.setVisibility(View.VISIBLE);
            }
            toolBar.setTitleLeft();
            toolBar.setTitle(name);

            switchPrice();
        }
    }

    /**
     * 切换显示价格
     */

    private void switchPrice() {
        if (mSockCoin != null) {
            String buyPrice = mSockCoin.getBuyPrice();
            String sellPrice = mSockCoin.getSellPrice();

            if (mActivity.status == 0) { //买入
                priceEdit.setText(sellPrice);
                limitPrice.setHint(sellPrice);
                realPrice = new BigDecimal(sellPrice);
            } else {
                priceEdit.setText(buyPrice);
                limitPrice.setHint(buyPrice);
                realPrice = new BigDecimal(buyPrice);
            }
        }
    }


    /**
     * 更改seekBar单位
     * 市价+买 -> USDT
     * 市价+卖 -> UNIT
     * 限价+买 -> UNIT
     * 限价+卖 ->UNIT
     */
    private void changeSeekBar() {
        transcationSeekbar.getConfigBuilder().min((float) min).max((float) max).build();
        if (orderType == SHIJIA && mActivity.status == 0) {
            transcationSeekbar.setCustomSectionTextArray(new TextArray(min, max, unitCoin));
            transactionType.setText(unitCoin);
            numEdit.setHint(App.INSTANCE.getString(R.string.strTransactionFragment68));
        } else {
            transactionType.setText(currencyType);
            transcationSeekbar.setCustomSectionTextArray(new TextArray(min, max, currencyType));
            if (mActivity.status == 0) {
                numEdit.setHint(App.INSTANCE.getString(R.string.strTransactionFragment68));
            } else {
                numEdit.setHint(App.INSTANCE.getString(R.string.strTransactionFragment68));
            }
        }

    }

    /**
     * 长连接更新买卖和最新价格信息
     *
     * @param data 数据源
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setBuySell(TransactionModel data) {
        if (buyAdapter != null && sellAdapter != null && data != null && data.getBids() != null && data.getAsks() != null) {
            Flowable.just(data)
                    .filter(item -> item.getCode().equals(code))
                    .compose(RxSchedulersHelper.transformer())
                    .subscribe(transactionModel -> {
                        if (mLoadingLayout != null) {
                            mLoadingLayout.setVisibility(View.INVISIBLE);
                        }
                        if (transactionModel.getAsks().size() >= buyNum) {
                            buyAdapter.setNewData(transactionModel.getBids().subList(0, buyNum));
                        }
                        if (transactionModel.getBids().size() >= buyNum) {
                            sellAdapter.setNewData(transactionModel.getAsks().subList(0, buyNum));
                        }

                    });
        }

    }

    /**
     * 格式化价格保留4位小数
     *
     * @param s price
     * @return price
     */
    public String priceFormat(String s) {
        if (!s.equals("---")) {
            return priceFormat.format(Double.parseDouble(s));
        }
        return s;
    }

    /**
     * 格式化数量保留3位小数
     *
     * @param s num
     * @return num
     */
    public String numFormat(String s) {
        if (!s.equals("---")) {
            return numFormat.format(Double.parseDouble(s));
        }
        return s;
    }


    /**
     * newInstance
     *
     * @return TransactionFragment
     */
    public static TransactionFragment newInstance() {
        TransactionFragment fragment = new TransactionFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void updateWallet(String wallone) {
        if (TextUtils.isEmpty(wallone)) {
            usdtMoney = "0.0";
        } else {
            usdtMoney = wallone;
        }
        upDate();
    }

    /**
     * SeekBar单位
     */
    class TextArray implements BubbleSeekBar.CustomSectionTextArray {
        double min;
        double max;
        String unit;

        TextArray(double min, double max, String unit) {
            this.min = min;
            this.max = max;
            this.unit = unit;
        }

        @NonNull
        @Override
        public SparseArray<String> onCustomize(int sectionCount, @NonNull SparseArray<String> array) {
            array.clear();
            array.put(0, String.valueOf(min));
            array.put(sectionCount, numFormat(String.valueOf(max)) + " " + unit);
            return array;
        }
    }

    public void setTextAndAnim(String text) {
        if (text.equals("---")) {
            return;
        }
        setText(priceEdit, text);
        ScaleAnimation scaleAnimation1 = new ScaleAnimation(1.0f, 1.5f, 1.0f, 1.4f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation1.setDuration(500);
        ScaleAnimation scaleAnimation2 = new ScaleAnimation(1.5f, 1f, 1.4f, 1f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation2.setDuration(500);
        scaleAnimation1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                priceEdit.startAnimation(scaleAnimation2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        priceEdit.startAnimation(scaleAnimation1);

    }

    /**
     * 计算最大最小购买数量
     * 设置滑杆最大最小值
     * 最大购买数量=余额/(（1+手续费)*price)
     */
    public void calculateMaxMin() {
        if (MyAppLication.isLogin()) { //登录
            //买
            if (mActivity.status == 0) {
                if (mSockCoin != null) {
                    limitPrice.setHint(mSockCoin.getBuyPrice());
                }

                if (orderType == SHIJIA) {
                    max = new BigDecimal(priceFormat.format(Double.valueOf(usdtMoney) / (1 + transFee))).doubleValue();
                    numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
                    maxTradeNum.setVisibility(View.GONE);
//                    maxTradeNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment76) + "  " + max + "  " + currencyType);

                } else {
                    maxTradeNum.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(priceEdit.getText()) && Double.valueOf(priceEdit.getText().toString()) != 0) {
                        maxBig = new BigDecimal(usdtMoney).divide(new BigDecimal(priceEdit.getText().toString().trim()).multiply(new BigDecimal("1").add(new BigDecimal(transFee))), 8, BigDecimal.ROUND_DOWN);
//                    double price = NumberUtils.pareDouble(priceEdit.getText().toString().trim());
//                    String divideFFloor = MathUtil.divideFFloorX(usdtMoney, (1 + transFee) * price);
//                    String s = priceFormat(divideFFloor);
                        max = Double.valueOf(NumberUtil.keep4(maxBig.doubleValue()));
                        maxTradeNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment76) + "  " + NumberUtil.keepMax8(maxBig.doubleValue()) + "  " + currencyType);
                    } else {
                        max = 0;
                        maxTradeNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment76) + "  " + max + "  " + currencyType);
                    }
//                    max = Float.parseFloat(numFormat(MathUtil.divideF(MathUtil.multiplyF(money, MathUtil.subtractF(1, transFee)), NumberUtils.pareFloat(priceEdit.getText().toString())) + ""));
                    numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
                    numEdit.setText("");
                }
                min = 0;
                usefulNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment88) + usdtMoney + "  " + unitCoin);

            } else {//卖
                if (mSockCoin != null) {
                    limitPrice.setHint(mSockCoin.getSellPrice());
                }
                maxTradeNum.setVisibility(View.GONE);
                max = Double.valueOf(haveNum);
                min = 0;
                usefulNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment88) + haveNum + "  " + currencyType);
                numEdit.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(8)});
            }
        } else {
            money = "0.0";
            max = 0;
            haveNum = 0 + "";
            if (mActivity.status == 0) {
                usefulNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment88) + money + "  " + unitCoin);
            } else {
                usefulNum.setText(App.INSTANCE.getString(R.string.strTransactionFragment88) + haveNum + "  " + currencyType);
            }
        }
        changeSeekBar();
    }

    /**
     * 计算总交易额
     */
    public void calculateTotalPrice() {

        if (orderType == SHIJIA) {
            if (mActivity.status == 0) { //买
                if (TextUtils.isEmpty(numEdit.getText().toString().trim())) {
                    transactionTotal.setText(App.INSTANCE.getString(R.string.strTransactionFragment98) + "0.0000" + "  " + unitCoin);
//                    TextSizeUtil.adjustTvTextSize(transactionTotal,transactionTotal.getWidth(),App.INSTANCE.getString(R.string.strTransactionFragment98) + "0.0000" + "  USDT");
                } else {
                    String trim = numEdit.getText().toString().trim();
                    transactionTotal.setText(App.INSTANCE.getString(R.string.strTransactionFragment98) + priceFormat.format(Double.valueOf(trim) * (1 + transFee)) + "  " + unitCoin);
//                    TextSizeUtil.adjustTvTextSize(transactionTotal,transactionTotal.getWidth(),App.INSTANCE.getString(R.string.strTransactionFragment98) + priceFormat.format(Double.valueOf(trim) * (1 + transFee)) + "  USDT");

                }
                transactionTotal.setVisibility(View.VISIBLE);
            } else { //卖
                if (TextUtils.isEmpty(numEdit.getText().toString().trim())) {

                    transactionTotal.setText(App.INSTANCE.getString(R.string.strTransactionFragment98) + "0.0000  " + currencyType);
                } else {
                    String trim = numEdit.getText().toString().trim();
                    transactionTotal.setText(App.INSTANCE.getString(R.string.strTransactionFragment98) + trim + "  " + currencyType);
                }

//                TextSizeUtil.adjustTvTextSize(transactionTotal,transactionTotal.getWidth(),App.INSTANCE.getString(R.string.strTransactionFragment98) + "---" + "  USDT");

//                transactionTotal.setVisibility(View.GONE);
            }
        } else {

            if (mActivity.status == 0) { //买
                String price = priceEdit.getText().toString().trim();
                BigDecimal priceBig = new BigDecimal(TextUtils.isEmpty(price) ? "0" : price);
                String num = numEdit.getText().toString().trim();
                BigDecimal numBig = new BigDecimal(TextUtils.isEmpty(num) ? "0" : num);
                BigDecimal totalBig = priceBig.multiply(numBig).multiply(new BigDecimal("1").add(new BigDecimal(transFee + "")));
                transactionTotal.setVisibility(View.VISIBLE);
                transactionTotal.setText(App.INSTANCE.getString(R.string.strTransactionFragment98) + NumberUtil.keepMax8(totalBig.toString()) + "  " + unitCoin);
//                TextSizeUtil.adjustTvTextSize(transactionTotal,transactionTotal.getWidth(),App.INSTANCE.getString(R.string.strTransactionFragment98) + NumberUtil.keep4(totalBig.toString()) + "  USDT");

            } else {
                String price = priceEdit.getText().toString().trim();
                BigDecimal priceBig = new BigDecimal(TextUtils.isEmpty(price) ? "0" : price);
                String num = numEdit.getText().toString().trim();
                BigDecimal numBig = new BigDecimal(TextUtils.isEmpty(num) ? "0" : num);
                BigDecimal totalBig = priceBig.multiply(numBig);
                transactionTotal.setVisibility(View.VISIBLE);
                transactionTotal.setText(App.INSTANCE.getString(R.string.strTransactionFragment98) + NumberUtil.keepMax8(totalBig.toString()) + "  " + unitCoin);
//                TextSizeUtil.adjustTvTextSize(transactionTotal,transactionTotal.getWidth(),App.INSTANCE.getString(R.string.strTransactionFragment98) + NumberUtil.keep4(totalBig.toString()) + "  USDT");

            }
        }

    }


    public void selectBuySell() {
        if (mActivity.status == 0) {
            transactionSelectBuy.setChecked(true);
        } else {
            transactionSelectSell.setChecked(true);
        }
    }

    /**
     * 检查登录状态
     */
    public void checkLogin() {
        if (MyAppLication.isLogin()) {
            historyAll.setVisibility(View.VISIBLE);
            if (mActivity.status == 0) { //买
                submitOrder.setText(App.INSTANCE.getString(R.string.strTransactionFragment19) + currencyType);
                submitOrder.setBackgroundResource(R.drawable.shape_bull_cyan_blue);
            } else { //卖
                submitOrder.setText(App.INSTANCE.getString(R.string.strTransactionFragment20) + currencyType);
                submitOrder.setBackgroundResource(R.drawable.shape_bull_red);
            }
        } else {
            submitOrder.setText(App.INSTANCE.getString(R.string.strTransactionFragment131));
            historyAll.setVisibility(View.GONE);
        }


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.TRANSACTION && resultCode == Activity.RESULT_OK) {
            upDate();
        }
    }

    @Subscribe(code = Constants.USER_LOGOUT, threadMode = ThreadMode.MAIN)
    public void logout() {

        upDate();//初始化界面
        transactionAdapter.setNewData(new ArrayList<>());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
